package com.tensquare.advice;

import java.util.List;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.tensquare.anntation.IgnoreResponseAdvice;
import com.tensquare.entity.Result;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by caoxingsheng.
 */
@RestControllerAdvice
@Slf4j
public class ResponseDataAdvice implements ResponseBodyAdvice<Object> {

	@Override
	public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
		// 判断controller类中是否有@IgnoreResponseAdvice
		if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
			log.info(methodParameter.getDeclaringClass().getName() + "有" + IgnoreResponseAdvice.class.getSimpleName()
					+ "注解");
			return false;
		}
		// 判断方法上是否有@IgnoreResponseAdvice
		if (methodParameter.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
			log.info(methodParameter.getMethod() + "有" + IgnoreResponseAdvice.class.getSimpleName() + "注解");
			return false;
		}

		return true;
	}
	@Nullable
	@Override
	public Object beforeBodyWrite(@Nullable Object object, MethodParameter methodParameter, MediaType mediaType,
			Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
			ServerHttpResponse serverHttpResponse) {
		log.info("ResponseDataAdvice.beforeBodyWrite");
		ServletServerHttpResponse response = (ServletServerHttpResponse)serverHttpResponse;
		int status = response.getServletResponse().getStatus();
		String reasonPhrase = null;
		for (HttpStatus httpStatus : HttpStatus.values()) {
			if (status == httpStatus.value()) {
				reasonPhrase = httpStatus.getReasonPhrase();
				break;
			}
		}
		Result result = new Result(status, reasonPhrase);
		if (null == object) {
			return result;
		} else if (object instanceof Result) {
			result = (Result) object;
		} else {
			result.setData(object);
		}
		return result;
	}
}
